package com.wu.controller.system;

import com.wu.aop.LogRecord;
import com.wu.base.ApiResponse;
import com.wu.base.ResultUtils;
import com.wu.enums.SystemEnum;
import com.wu.exception.BusinessException;
import com.wu.pojo.reqeust.sys.LoginRequest;
import com.wu.pojo.reqeust.sys.PhoneLoginRequest;
import com.wu.redis.RedisService;
import com.wu.service.sys.SUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@Api(value = "登录相关接口", tags = {"登录相关接口"})
@RequestMapping(value = "/sys")
@Slf4j
public class LoginController {

    @Resource
    private SUserService userService;
    @Resource
    private RedisService redisService;

    @ApiOperation(value = "登录", notes = "用户登录")
    @PostMapping(value = "/login")
    @LogRecord(value = "登录")
    public ApiResponse login(@Validated() @RequestBody LoginRequest request) {
        repeat("/sys/login_" + request.getUsername());
        return userService.login(request);
    }

    @ApiOperation(value = "手机号-验证码登录")
    @PostMapping(value = "/phoneLogin")
    @LogRecord(value = "验证码登录")
    public ApiResponse phoneLogin(@Validated @RequestBody PhoneLoginRequest request) {
        repeat("/sys/phoneLogin_" + request.getPhone());
        return userService.phoneLogin(request);
    }

    @ApiOperation(value = "退出")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ApiResponse logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultUtils.setOk();
    }

    private void repeat(String key) {
        boolean hasKey = redisService.hasKey(key);
        if (hasKey) {
            throw new BusinessException(SystemEnum.REPEAT_OPERATION);
        }
        redisService.set(key, System.currentTimeMillis(), 1);
    }
}
